/**
 *
 * @file validtor
 * @author fanxueliang@qq.com
 */
import type {ValidateResult, RulesFunType} from './interface';
import {rules} from './rules';
import type {RulesItem, RulesKey} from '../interface/spec';
import {curry} from 'lodash-es';

export interface ValidatorType {
    rules: RulesItem;
    genValidators: () => ValidateFunType[];
}

export type ValidateFunType = (validateValue: any, parentValue?: any) => ValidateResult;
export class Validator implements ValidatorType {
    rules: RulesItem;

    constructor(rulesItem: RulesItem) {
        this.rules = rulesItem;
    }

    genValidators(): ValidateFunType[] {
        const result: ValidateFunType[] = [];
        Object.keys(this.rules).forEach((item) => {
            const key = item as RulesKey;
            const values = this.rules[key];
            const fun = rules[key];
            if (typeof fun === 'function') {
                let genValidateFun;
                if (key === 'jsRule') {
                    genValidateFun = (
                        fun: RulesFunType<RulesKey>,
                        values: any,
                        validateValue: any,
                        parentValue: any
                    ): ValidateResult => {
                        return fun(validateValue, values, parentValue);
                    };
                } else {
                    genValidateFun = (fun: RulesFunType<RulesKey>, values: any, validateValue: any): ValidateResult => {
                        return fun(validateValue, values);
                    };
                }
                const curried = curry(genValidateFun)(fun, values);
                result.push(curried);
            }
        });
        return result;
    }
}
